<template>
  <form
    :class="{
      'is-focusd': focus || disableFouce,
      transparent
    }"
    @submit.prevent
    class="search"
    action="#"
  >
    <div class="search-input">
      <div
        ref="syntheticPhRef"
        :style="{
          width: focus || searchValue ? calcSyntheticPhContainerWidth() : '100%',
        }"
        class="search-placeholder"
      >
        <span ref="syntheticPhContainerRef">
          <i class="jeicon je-icon jeicon-search" />
          <span :style="{visibility: searchValue ? 'hidden' : 'visible'}"> {{ placeholder }} </span>
        </span>
      </div>
      <input
        id="inputFocus"
        ref="searchInput"
        v-if="!modelType"
        :value="searchValue"
        @focus="changeFocus('true')"
        @blur="changeFocus('false')"
        @input="handleInput"
        type="text"
      >
      <input
        id="inputFocus"
        ref="searchInput"
        v-if="modelType"
        :value="searchValue"
        @focus="changeFocus('true')"
        @blur="changeFocus('false')"
        @compositionend="compositionend"
        @input="handleInput"
        type="text"
      >
      <i
        v-show="searchValue"
        @tap="handleClearClick"
        class="jeicon je-icon jeicon-error-circle"
      />
    </div>
    <div
      v-if="!hideCancel"
      :class="{
        transparent
      }"
      @tap="handleCancelClick"
      class="search-cancel search-cancel-anim"
    >
      取消
    </div>
  </form>
</template>

<script>
export default {
  name: 'SearchInput',
  props: {
    placeholder: {
      type: String,
      default: '搜索',
    },
    searchValue: {
      type: String,
      default: '',
    },
    transparent: {
      type: Boolean,
      default: false,
    },
    disableFouce: {
      type: Boolean,
      default: false,
    },
    hideCancel: {
      type: Boolean,
      default: false,
    },
    /**
     * 是否自动获取焦点
     * 如果是预加载的页面，此项应该设为false。
     * 后续通过ref调用 showSoftInput 来打开
     * 新打开的页面应该使用true。自动打开
     */
    autoFocus: {
      type: Boolean,
      default: false,
      flag: false,
    },
  },
  data() {
    return {
      focus: false,
      nativeWebview: '',
      imm: '',
      flag: false,
      InputMethodManager: '',
      modelType: '',
    };
  },

  created() {
    const { autoFocus } = this.$props;
    this.initNativeObjects();
    if (autoFocus) {
      setTimeout(() => {
        this.showSoftInput();
      }, 300);
    }
    mui.os.ios ? this.modelType = true : '';
  },
  mounted() {
  },
  methods: {
    compositionend() {
      // 输入完成再执行
      this.flag = true;
      this.handleInput();
    },
    handleInput() {
      if (this.flag) {
        this.$emit('update:searchValue', this.$refs.searchInput.value);
        if (!this.$refs.searchInput.value) {
          this.flag = false;
        }
      } else {
        this.$emit('update:searchValue', this.$refs.searchInput.value);
      }
    },
    handleClearClick() {
      this.$emit('clearKey');
    },
    handleCancelClick() {
      this.$refs.searchInput.blur();
      this.$emit('update:searchValue', '');
      this.$emit('cancel');
    },
    calcSyntheticPhContainerWidth() {
      const { syntheticPhContainerRef } = this.$refs;
      const realWidth = syntheticPhContainerRef.getBoundingClientRect()
        .width; // 包含小数
      return `${Math.ceil(realWidth + 5)}px`;
    },
    changeFocus(type) {
      this.focus = type === 'true';
      this.$emit('focus', this.focus);
    },
    initNativeObjects() {
      const nativeWebview = plus.webview.currentWebview().nativeInstanceObject();
      if (mui.os.android) {
        const main = plus.android.runtimeMainActivity();
        const Context = plus.android.importClass('android.content.Context');
        this.InputMethodManager = plus.android.importClass('android.view.inputmethod.InputMethodManager');
        this.imm = main.getSystemService(Context.INPUT_METHOD_SERVICE);
        // 强制当前webview获得焦点
        plus.android.importClass(nativeWebview);
      } else {
        this.nativeWebview = plus.webview.currentWebview().nativeInstanceObject();
      }
    },
    showSoftInput() {
      const nativeWebview = plus.webview.currentWebview().nativeInstanceObject();
      if (mui.os.android) {
        nativeWebview.requestFocus();
        this.imm.toggleSoftInput(0, this.InputMethodManager.SHOW_FORCED);
      } else {
        nativeWebview.plusCallMethod({
          setKeyboardDisplayRequiresUserAction: false,
        });
      }
      setTimeout(() => {
        this.$refs.searchInput.focus();
      }, 100);
    },
  },
};
</script>

<style lang="less" scoped>
@import "~@/theme/variable.less";

.search {
  display: flex;
  padding: 8px 10px;
  padding-right: 30px;
  overflow: hidden;
  &.transparent {
    background-color: transparent;
  }
  .search-input {
    position: relative;
    flex: 1;
    height: 60px;
    line-height: 60px;
    caret-color: #fff;
    border-radius: 30px;
    font-size: @font-size-base;
    background-color: #fff;
    .search-placeholder {
      width: 100%;
      text-align: left;
      transition: all 0.3s;
      // z-index: 100;
    }
    i {
      margin-right: 5px;
      padding-left: 15px;
    }
    input {
      width: 100%;
      padding: 0 48px 0 60px;
      caret-color: #333;
      color: #333;
      height: 60px;
      font-size: @font-size-base;
      background: transparent;
      border: 0;
    }
    // @supports (-webkit-mask: none) and (not (cater-color: red)) {
    //   input {
    //     color: #fff;
    //   }
    //   input::first-line {
    //     color: #fff;
    //   }
    // }
    .jeicon-error-circle {
      position: absolute;
      right: 0;
      top: 0;
      color: #cccccc;
    }
  }
  .search-placeholder,
  input[type="text"] {
    position: absolute;
    left: 0;
    top: 0;
    color: #ccc
  }
  input[type="text"] {
    color: #333;
  }
  .search-cancel {
    height: 60px;
    line-height: 60px;
    margin-left: 40px;
    margin-right: -68px;
    color: #fff;
  }
  &.is-focusd {
    .search-cancel {
      margin-right: 0px;
    }
  }
}

.search-cancel-anim {
  transition: margin-right 0.3s, opacity 0.3s;
  transition-delay: 0.1s;
}
</style>
